<template>
  <el-tabs type="border-card">
    <el-tab-pane label="商品基本信息">
      <el-form ref="form" :model="goodsForm" label-width="120px">
        {{goodsForm}}
        <el-form-item label="商品分类" style="width: 90%">
          <el-select v-model="goodsForm.goods.category1Id" placeholder="一级分类">
            <el-option
              v-for="item in categorys1"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="goodsForm.goods.category2Id" placeholder="二级分类">
            <el-option
              v-for="item in categorys2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="goodsForm.goods.category3Id" placeholder="三级分类">
            <el-option
              v-for="item in categorys3"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
            {{goodsForm.goods.typeTemplateId}}
        </el-form-item>
        <el-form-item label="商品名称" style="width: 90%">
          <el-input v-model="goodsForm.goods.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="商品品牌" style="width: 90%">
          <el-select v-model="goodsForm.goods.brandId" placeholder="商品品牌">
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品副标题" style="width: 90%">
          <el-input v-model="goodsForm.goods.caption"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" style="width: 90%">
          <el-input v-model="goodsForm.goods.price"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍" style="width: 90%">
          <el-input v-model="goodsForm.goodsDesc.introduction"></el-input>
        </el-form-item>
        <el-form-item label="包装列表" style="width: 90%">
          <el-input v-model="goodsForm.goodsDesc.packageList"></el-input>
        </el-form-item>
        <el-form-item label="售后服务" style="width: 90%">
          <el-input v-model="goodsForm.goodsDesc.saleService"></el-input>
        </el-form-item>
      </el-form>
    </el-tab-pane>

    <el-tab-pane label="商品图片">
      <el-button type="primary" round @click="newUpload">新建图片</el-button>
      <el-table
        :data="goodsForm.goodsDesc.itemImages"
        style="width: 100%">

        <el-table-column
          prop="color"
          label="颜色"
          align="center"
          width="180">
        </el-table-column>
        <el-table-column
          label="图片"
          align="center"
          width="180">
          <template slot-scope="scope">
            <img :src="scope.row.url" width="100"/>
          </template>
        </el-table-column>

        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="goodsForm.goodsDesc.itemImages.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-tab-pane>
    <el-tab-pane label="扩展属性">
      <el-table
        :data="goodsForm.goodsDesc.customAttributeItems"
        style="width: 100%">
        <el-table-column
          align="center"
          width="180">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>

        <el-table-column
          label="图片"
          align="center"
          width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.value" placeholder="属性名称"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="规格">
<!--      展示规格及规格列表-->
      <el-table
        :data="specs"
        style="width: 100%">
        {{this.specs}}
        <el-table-column
          width="200">
          <template slot-scope="scope">
            {{scope.row.attributeName}}
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
              <el-checkbox-group v-model="optionList[scope.$index]" @change="userSelect" >
              <el-checkbox v-for="attr in scope.row.attributeValues" :label="attr"  border/>
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>
<!--      展示选中的sku商品表-->
      <el-table
        :data="goodsForm.itemList"
        style="width: 100%">
        <el-table-column
          v-for="(specfication,key) in goodsForm.goodsDesc.specificationItems"
          :key="key"
          align="center"
          :label="specfication.attributeName"
          width="200">
          <template slot-scope="scope">
            {{scope.row.spec[specfication.attributeName]}}
          </template>
        </el-table-column>
        <el-table-column label="价格" align="center">
          <template slot-scope="scope">
          <el-input type="text" v-model="scope.row.price"/>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center">
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.num"/>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>

<!--    定义文件上传的对话框-->
    <el-dialog
      title="上传商品图片"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="50%">
      {{imageEntity}}
      <el-form :model="imageEntity">
      <el-form-item label="颜色">
        <el-input v-model="imageEntity.color" />
      </el-form-item>
      <el-form-item label="图片上传">
        <el-upload
          action="#"
          list-type="picture-card"
          :file-list="fileList"
          :http-request="uploadFile">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <span class="el-upload-list__item-actions">
        <span class="el-upload-list__item-preview">
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete">
          <i class="el-icon-download"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete">
          <i class="el-icon-delete"></i>
        </span>
      </span>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item style="text-align: right">
        <el-button type="primary" @click="savePic">保 存</el-button>
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </el-form-item>
      </el-form>
    </el-dialog>
    <div style="margin-top: 10px;">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button>返回列表</el-button>
    </div>
  </el-tabs>


</template>

<script>
  export default {
    data () {
     return {
       categorys1:[], //代表一级分类
       categorys2:[], //代表2级分类
       categorys3:[], //代表3级分类
       brandList:[],  //根据模板id得到品牌列表
       //goodsForm下面是组合类对象，数组
       dialogVisible:false,  //文件上传对话框是否显示
       imageEntity:{}, //代表上传的图片对象
       fileList:[],  //图片的文件列表
       optionList:[], //绑定的当前用户选择的所有的规格及规格选项的值
       specName:[],  //当前模板对应的所有规格的名字
       specs:[],    //某个模板id对应的规格及规格选项的列表值
       goodsForm:{
         goods:{typeTemplateId:''},
         goodsDesc:{itemImages: [],customAttributeItems:[],specificationItems:[]},
         itemList:[],
       }
      }
    },
    created() {
      //查询一级分类
      this.findCategoryById(0)
      //处理修改请求，根据传入的id查询商品详细信息
      this.findById()
    },
    //监听指定属性值的改变
    watch:{
      //写法一：过于臃肿
      // "goodsForm.goods.category1Id"(newV,oldV){
      //   console.log("oldV:",oldV,"llllnewV",newV)
      // },
      //一级分类改变，就查询出对应的二AAAAA级分类列表
      category1Idnew(newV,oldV){
        console.log("AAA")
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("bbbbb")
            this.categorys2= data.list;
            console.log("ppp",data.list)
            console.log("ccccc")

            //清空下级
            // delete this.goodsForm.goods.category2Id
            // delete this.goodsForm.goods.typeTemplateId
          }
        })
    },
      //二级分类的变化查询出三级分类列表
      category2Idnew(newV,oldV){
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categorys3= data.list;
            console.log("adddd",data)

            // delete this.goodsForm.goods.category3Id
          }
        })
      },
      //三级分类发生变化导致模板id变化
      category3Idnew(newV,oldV){
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/info/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.goodsForm.goods.typeTemplateId= data.itemCat.typeId;
            console.log("adddd",this.goodsForm.goods.typeTemplate
            )
            // delete this.goodsForm.goods.typeTemplateId
          }
        })
      },
      //根据模板id的值，查询出品牌列表
      typeTemplateIdnew(newV,oldV){
        console.log("aaaaaa:",newV)
        this.$http({
          url: this.$http.adornUrl(`/shop/typetemplate/info/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data",data)
            //1，为品牌列表赋值
            this.brandList =JSON.parse( data.typeTemplate.brandIds)
            //2，为扩展属性赋值 当模板id发生变化时，将自定义扩展属性赋值给this.goodsForm.goodsDesc.customAttributeItems
            if (!this.$route.query.id){
              this.goodsForm.goodsDesc.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems)
            }

            //3，根据模板id发生变化时，将规格及规格选项列表查询出来
            let specIds =JSON.parse(data.typeTemplate.specIds)
            //4,每次模板id发生变化时，将清空
            this.specs=[]   //定义的数组变量，specs用于展示规格页面的元素
            //5，便利规格，并为规格及规格选项进行赋值
            specIds.forEach(spec=>{
              let attValues =[];  //代表规格选项数组
              this.optionList.push([])  //1,放一个空数组代表，代表规格的个数与optionList里的小数组个数一样
              this.specName.push(spec.text)  //2, 将挡前的规格的名字放到数组中
              this.$http({
                url: this.$http.adornUrl(`/shop/specificationoption/findOptions/${spec.id}`),
                method: 'get'
              }).then(({data}) => {
                if (data && data.code === 0) {
                  //放规格选项到数组中
                  attValues =data.options.map(m=>m.optionName)
                  //为零时数组变量赋值
                  this.specs.push({"attributeName":spec.text,"attributeValues":attValues})
                  console.log('attValues',attValues)
                }
              })
            })
            console.log('this',this.specs)
          }
        })
      },
    },
    //借助自动计算功能
    computed:{
      // 检测goodsForm.goods.category1Id的属性值是否发生改变，若改变则category1Idnew也会改变。
      category1Idnew(){
        return this.goodsForm.goods.category1Id
      },
      // 检测goodsForm.goods.category1Id的属性值是否发生改变，若改变则category2Idnew也会改变。
      category2Idnew(){
        return this.goodsForm.goods.category2Id
      },
      // 检测goodsForm.goods.category3Id的属性值是否发生改变，若改变则category2Idnew也会改变。
      category3Idnew(){
        return this.goodsForm.goods.category3Id
      },
      typeTemplateIdnew(){
        return this.goodsForm.goods.typeTemplateId
      }
    },
    methods: {
      //拿到修改id  进修修改
      findById(){
        let id = this.$route.query.id
       //根据商品id从数据库查询出spu商品，spu商品描述。
        //发送请求
        if(id){
          this.$http({
            url: this.$http.adornUrl(`/shop/goods/findById/${id}`),
            method: 'get',
          }).then(({data}) => {
            if (data && data.code === 0) {
              console.log("goods",data.goods)
              //为商屏信息赋值，商评描述，列表赋值
              this.goodsForm = data.goods
              this.goodsForm.goodsDesc.customAttributeItems = JSON.parse(this.goodsForm.goodsDesc.customAttributeItems)
              this.goodsForm.goodsDesc.itemImages = JSON.parse(this.goodsForm.goodsDesc.itemImages)
              this.goodsForm.goodsDesc.specificationItems = JSON.parse(this.goodsForm.goodsDesc.specificationItems)
              this.goodsForm.itemList.forEach(item=>{
                item.spec = JSON.parse(item.spec)
              })
              //让规格自动选中{为optionList}的数组赋值
              this.goodsForm.goodsDesc.specificationItems.forEach(spec=>{
                this.optionList.push(spec.attributeValue)
              })
            }
          })
        }

      },
      //根据父id查子类
      findCategoryById(pid){
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${pid}`),
          method: 'get',

        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categorys1 = data.list;
            console.log("22",this.categorys1)
          }
        })
      },

      //进行文件上传
      uploadFile(v){
        //以前的文件上传：（同步上传）
        //① 表单必须是post的请求
        //②表单的enctype="multipart/form-data"
        // 现在异步提交
        //①利用H5的formData对象模拟表单数据
        let data = new FormData();
        data.append("file",v.file)
        // this.fileList=[]
        //② 发出上传请求,将上传的文件放到文件列表中
        this.$http({
          url: this.$http.adornUrl(`/thirdParty/uploadFile`),
          method: 'post',
          headers:{"Content-Type":"multipart/form-data"},
          data
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("url",data.url)
            this.imageEntity.url = data.url
            this.fileList.push({name:v.raw,url:data.url})
          }
        })

      },
      newUpload(){
        this.imageEntity = {};
        this.fileList = []
        this.dialogVisible = true
      },
      //保存
      savePic(){
        //加到数组中 将imagerEntity添加到ItemImages
        this.goodsForm.goodsDesc.itemImages.push(this.imageEntity)
        //关闭对话框。
        this.dialogVisible = false
      },
      //用户选择
      userSelect(v){
        console.log("须知",this.optionList)
        //1,定义用户选择器
        let specItems =[]
        for (let i=0; i<this.specName.length;i++){
         if (this.optionList[i].length>0){
           specItems.push({"attributeName":this.specName[i],"attributeValue":this.optionList[i]})
         }
        }

        //2,将上面的specItems赋值给this.goodsFrom.goodsDesc.specificationItems

        this.goodsForm.goodsDesc.specificationItems=specItems

        // 3，为sku商品列表添加数据
        this.createItemList();
      },
      //6.创建sku列表的默认数据
      createItemList(){
        //定义sku列表的默认值数据
        this.goodsForm.itemList = [{spec:{},num:9999,price:100,status:0,isDefault:0}]
        //得到当前用户勾选的规格选项列表
        let items = this.goodsForm.goodsDesc.specificationItems;
        //将items的值赋值给this.goodsForm.itemList这个商品列表
        if(items != null && items.length > 0){
          items.forEach(item=>{
            this.goodsForm.itemList = this.addColumn(this.goodsForm.itemList,item.attributeName,item.attributeValue)
          })
        }
      },
      //7. 为sku商品列表赋值
      addColumn(items,attrName,attrValue){
        //定义一个新数数组
        let newList = []
        //遍历items并赋值
        items.forEach(item=>{
          attrValue.forEach(v=>{
            //通过克隆得到一个新行数据
            let newRow = JSON.parse(JSON.stringify(item))    // 代表将item进行深克隆，这样得到两个对象不再有绑定关系
            //为新行的spec属性赋值
            newRow.spec[attrName] = v
            //添加新行给newList这个数组
            newList.push(newRow)
          })
        })
        return newList
       },
      //添加商品
      save(){
        //先处理提交到后台的数据
        this.goodsForm.itemList.forEach(item=>{
          item.spec = JSON.stringify(item.spec)
        })
        //转化为字符串
        this.goodsForm.goodsDesc.itemImages = JSON.stringify(this.goodsForm.goodsDesc.itemImages)
        this.goodsForm.goodsDesc.customAttributeItems = JSON.stringify(this.goodsForm.goodsDesc.customAttributeItems)
        this.goodsForm.goodsDesc.specificationItems = JSON.stringify(this.goodsForm.goodsDesc.specificationItems)
        //提交请求
        //判断是为添加还是修改
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/${this.$route.query.id ? 'update' : 'save'}`),
          //post请求
          method: 'post',
          //加参数
          data:this.goodsForm
        }).then(({data}) => {
          if (data && data.code === 0) {
            //添加成功后，恢复为默认值
            this.goodsForm ={goods: {},goodsDesc: {specificationItems: {},itemImages: {},customAttributeItems: {}},itemList: []}
            this.imageEntity={}
            this.fileList=[]
            this.optionList=[]
          }
        })
      },
    }
  }
</script>
<!--<style>-->
<!--  .avatar-uploader .el-upload {-->
<!--    border: 1px dashed #d9d9d9;-->
<!--    border-radius: 6px;-->
<!--    cursor: pointer;-->
<!--    position: relative;-->
<!--    overflow: hidden;-->
<!--  }-->
<!--  .avatar-uploader .el-upload:hover {-->
<!--    border-color: #409EFF;-->
<!--  }-->
<!--  .avatar-uploader-icon {-->
<!--    font-size: 28px;-->
<!--    color: #8c939d;-->
<!--    width: 178px;-->
<!--    height: 178px;-->
<!--    line-height: 178px;-->
<!--    text-align: center;-->
<!--  }-->
<!--  .avatar {-->
<!--    width: 178px;-->
<!--    height: 178px;-->
<!--    display: block;-->
<!--  }-->
<!--</style>-->
